import time,datetime
def write_a(ip):
    now='##'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    ip=ip.replace('\n','')
    if ip=='':
        pass
    elif len(ip)<9:
        pass
    else:
        with open('/etc/hosts.deny','a')as f:
#            print(f.readlines())
            f.write('sshd:{}\n{}\n'.format(ip,now))


def deal(line):
    
    if "Invalid" in line:
        ip=(line.split('from')[1].split(' ')[1])

    elif 'Failed password' in line:
#        print(line)
        ip=(line.split('from')[1].split(' ')[1])
        print('Failed password',ip,line)

    elif 'rhost' in line:
        #pass
        ip=(line.split('rhost=')[1].split(' ')[0])
        print('rhost',ip)

    elif 'error' in line or 'refused' in line:
        ip=''
    elif 'Disconnected' in line or 'disconnect' in line:
        ip=''
    elif 'warning' in line:
        ip=''
    else:
        print('pass',line)
        ip=''
    if ip in black_ip_list:
        pass
    else:
        black_ip_list.append(ip)
        write_a(ip)

black_ip_list=['']
with open('/var/log/secure','r')as f:
    f.seek(0,2)
    while True:
        time.sleep(1)

        line=f.readline()
        if line:
            print(line)
            deal(line)
